﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NHibData;
using NHibData.Attributes;
using StudyEnglish.Application.Service;
using StudyEnglish.Model;
using StudyEnglish.Models;
using StudyEnglish.Service;

namespace StudyEnglish.Controllers
{
    public class DictionaryController : BaseController
    {
        //
        // GET: /Dictionary/

        public ActionResult Index()
        {
            var items = DataService.Dictionary.FindAllItems();
            var dict = new DictionaryModel(items);
            
            return View(dict);
        }

        [Transaction]
        public string UpdateElement(string value, int? row_id, int? column)
        {
            if(row_id == null || column == null)
                throw new ArgumentNullException("row_id or column can't be null");


            DictionaryItem item = DataService.Dictionary.GetById(row_id.Value);
            switch(column)
            {
                case 1:
                    item.Name = value;
                    break;
                case 2:
                    item.Descr = value;
                    break;
                case 3:
                    item.Key = value;
                    break;
            }
            DataService.Dictionary.UpdateItem(item);
            return value;
        }

        [Transaction]
        public ActionResult Analyze()
        {
            var items = DataService.Dictionary.FindAllItems();
            var files = DataService.FileService.FindAllFiles();

            foreach (var file in files)
            {
                file.RelatedDictionaryItems.Clear();
                if(string.IsNullOrEmpty(file.InitialFilePath) == false)
                {
                    foreach (var item in items)
                    {
                        AnalyzeFile(file, item);       
                    }
                }
            }
            
            return RedirectToAction("Index");
        }

        private void AnalyzeFile(File file, DictionaryItem item)
        {
            //var separators = new char[] {',', ' ', '\\', '/', ';'};
            var path = file.InitialFilePath.Trim().ToLower();

            var itemKeys = new List<string> {item.Key, item.Name};
            bool findMatch = false;
            foreach (var itemKey in itemKeys)
            {
                if(string.IsNullOrWhiteSpace(itemKey) == false)
                {
                    var keyToCheck = itemKey.Trim().ToLower();
                    if(path.Contains(keyToCheck))
                    {
                        findMatch = true;
                    }
                }
            }

            if(findMatch)
            {
                file.RelatedDictionaryItems.Add(item);
                DataService.FileService.UpdateFile(file);
            }
        }
    }
}
